package com.gaojice.server.http.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URISyntaxException;
import java.util.List;

import com.gaojice.ftp.server.FtpService;
import com.gaojice.server.constants.Constants;
import com.gaojice.server.http.model.FileItem;
import com.gaojice.server.http.model.Request;
import com.gaojice.server.http.model.Response;
import com.gaojice.server.http.model.ResponseHeader;

public class ResponseService {

	public Response getResponse(Request request) throws URISyntaxException,
			IOException {
		Response response = new Response();
		ResponseHeader responseHeader = new ResponseHeader();
		StringBuffer headerString = new StringBuffer("HTTP/1.1 200 OK\n");
		String responseBody = "No body";
		if (request.isFile()) {
			String path = Constants.ROOT_DIR
					+ request.getHeader().getRequestPath();
			File file = new File(path);
			if (!file.exists()) {
				response
						.setResponseTextBody("File Not Found!" + file.getName());
				return response;
			}
			headerString.append("Content-Type: APPLICATION/OCTET-STREAM\n");
			headerString.append("Content-Disposition: attachment; filename="
					+ request.getHeader().getRequestPath() + "\n");
			headerString.append("Content-Length: " + file.length() + "\n");
			response.setResponseStreamBody(new FileInputStream(file));

		} else {
			headerString.append("Content-Type: text/html; charset=utf-8\n");
			List<FileItem> fileItems = new FileItemService()
					.getFileItems(request.getHeader().getRequestPath());
			StringBuffer contentBuffer = new StringBuffer();
			for (FileItem fileItem : fileItems) {
				contentBuffer.append(fileItem.toString());
			}
			responseBody = generateHtml(contentBuffer.toString());
			response.setResponseTextBody(responseBody);
		}
		responseHeader.setHeaderContent(headerString + "\n");
		response.setResponseHeader(responseHeader);
		return response;
	}

	public void response(Response response, Socket socket) throws IOException {
		BufferedWriter bufferedWriter = new BufferedWriter(
				new OutputStreamWriter(socket.getOutputStream()));
		bufferedWriter.write(response.getResponseHeader().getHeaderContent());
		bufferedWriter.flush();
		FileInputStream fileInputStream = response.getResponseStreamBody();
		if (fileInputStream != null) {

			byte[] data = new byte[1024];
			while (fileInputStream.available() > 0) {
				fileInputStream.read(data, 0, 1024);
				socket.getOutputStream().write(data);
			}
			fileInputStream.close();
		} else {
			bufferedWriter.write(response.getResponseTextBody());
		}
		bufferedWriter.flush();
		bufferedWriter.close();
	}

	public String getUiTemplate() throws URISyntaxException, IOException {

		return FtpService.uitemplate;
		// return
		// "<form action=\"/\" enctype=\"MULTIPART/FORM-DATA\" method=post><input type=\"file\" name=\"filename\" /><input type=\"submit\" value=\"上载\" /></form><br><table>${}</table>";
	}

	public String generateHtml(String content) throws URISyntaxException,
			IOException {
		String template = getUiTemplate();
		while (template.contains("$")) {
			template = template.replaceFirst("\\$\\{.*\\}", content);
		}
		return template;
	}

}
